<template>
  <div class="header-container">
    <!-- 头部模块 -->
    <div class="header container">
      <h2 class="left"><span>内容</span>管理系统</h2>
      <div class="right">
        <template v-if="!isLogin">
          <span @click="loginDialogVisible = true">登录</span>
          <span @click="registeDialogVisible = true">注册</span>
        </template>
        <div v-else class="userInfo">
          <div class="username">
            <i class="el-icon-user" />
            {{ userInfo.username }}
          </div>
          <div class="logout" @click="logout"><i class="el-icon-switch-button" />退出</div>
        </div>
      </div>
    </div>

    <!-- 菜单栏 -->
    <div class="menu">
      <div class="container">
        <el-menu
          router
          :default-active="$route.fullPath"
          mode="horizontal"
          background-color="#333"
          text-color="#fff"
          active-text-color="#27ba9b"
        >
          <el-menu-item index="/home">首页</el-menu-item>
          <template v-for="item in cateList">
            <el-menu-item v-if="!item.children" :index="`/lists/${item.id}`" :key="item.id + ''">
              {{ item.name }}
            </el-menu-item>
            <el-submenu v-else :index="`/lists/${item.id}`" :key="item.id">
              <template slot="title">{{ item.name }}</template>
              <el-menu-item :index="`/lists/${sub.id}`" v-for="sub in item.children" :key="sub.id">
                {{ sub.name }}
              </el-menu-item>
            </el-submenu>
          </template>
        </el-menu>
      </div>
    </div>

    <!-- 登录弹出框 -->
    <el-dialog
      title="登录"
      :visible.sync="loginDialogVisible"
      width="35%"
      @close="loginDailogClose"
    >
      <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef" label-position="top">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="loginDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="login">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 注册弹出框 -->
    <el-dialog
      title="注册"
      :visible.sync="registeDialogVisible"
      width="35%"
      @close="registeDailogClose"
    >
      <el-form
        :model="registeForm"
        :rules="registeFormRules"
        ref="registeFormRef"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registeForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registeForm.email"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registeForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input type="password" v-model="registeForm.password2"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="registeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="registe">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqCateList, login, registe } from '@/api'
import bus from '@/eventBus'

export default {
  name: 'MyHeader',
  data() {
    // 用户名验证规则
    const username = [
      { required: true, message: '请输入登录名称', trigger: 'change' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' }
    ]
    // 密码验证规则
    const password = [
      { required: true, message: '请输入登录密码', trigger: 'change' },
      { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'change' }
    ]
    // 邮箱验证规则
    const email = [
      { required: true, message: '请输入邮箱地址', trigger: 'change' },
      { type: 'email', message: '请输入正确的邮箱地址' }
    ]
    // 自定义确认密码验证规则
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registeForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 确认密码验证规则
    const password2 = [{ validator: validatePass2, trigger: 'change' }]

    return {
      // 分类导航列表
      cateList: [],
      // 控制登录弹出框的显示与隐藏
      loginDialogVisible: false,
      // 登录表单对象
      loginForm: {
        username: 'test',
        password: '123456'
      },
      // 登录表单验证规则对象
      loginFormRules: {
        // 验证用户名是否合法
        username,
        // 验证密码是否合法
        password
      },
      // 控制注册弹出框的显示与隐藏
      registeDialogVisible: false,
      // 注册表单对象
      registeForm: {
        username: '',
        email: '',
        password: '',
        password2: ''
      },
      // 注册表单验证规则对象
      registeFormRules: {
        // 验证用户名是否合法
        username,
        // 验证密码是否合法
        password,
        // 验证邮箱是否合法
        email,
        // 验证确认密码是否合法
        password2
      },
      // 登录验证
      isLogin: !!localStorage.getItem('token'),
      // 获取信息
      userInfo: null
    }
  },
  created() {
    this.getCateList()
    this.userInfo = JSON.parse(localStorage.getItem('userInfo')) || {}
    bus.$on('visible', val => {
      this.loginDialogVisible = val
    })
    // 监听窗口大小
    window.addEventListener('resize', this.resizeObserver)
  },
  methods: {
    // 获取分类列表
    async getCateList() {
      const { data: res } = await reqCateList()
      this.cateList = res
    },
    // 用户登录
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await login(this.loginForm)
        // 登录失败
        if (res.status !== 200) return this.$message.error(res.msg)
        localStorage.setItem('userInfo', JSON.stringify(res.userInfo))
        localStorage.setItem('token', res.token)
        this.isLogin = true
        this.userInfo = res.userInfo
        // 登录成功
        this.$message.success(res.msg)
        // 关闭弹出框
        this.loginDialogVisible = false
      })
    },
    // 监听弹出框的关闭信息
    loginDailogClose() {
      this.$refs.loginFormRef.resetFields()
    },
    // 用户注册
    registe() {
      this.$refs.registeFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await registe(this.registeForm)
        // 注册失败
        if (res.status !== 200) return this.$message.error(res.msg)
        // 注册成功
        this.$message.success(res.msg)
        // 关闭弹出框
        this.registeDialogVisible = false
      })
    },
    // 监听弹出框的关闭信息
    registeDailogClose() {
      this.$refs.registeFormRef.resetFields()
    },
    // 退出登录
    logout() {
      this.$confirm('是否确定退出登录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除用户信息
          localStorage.removeItem('userInfo')
          // 删除token
          localStorage.removeItem('token')
          this.isLogin = false
          this.$message({ type: 'success', message: '退出登录成功' })
        })
        .catch(() => this.$message({ type: 'info', message: '已取消退出登录' }))
    }
  }
}
</script>

<style lang="less">
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100px;

  h2 {
    font-weight: 400;
    font-size: 26px;

    span {
      color: @primaryColor;
    }
  }

  .right {
    span {
      transition: all 0.35s;
      cursor: pointer;

      & ~ span {
        margin-left: 10px;
      }

      &:hover {
        color: @primaryColor;
      }
    }

    .userInfo {
      display: flex;
      font-size: 16px;

      i {
        margin-right: 5px;
      }

      .username {
        color: @primaryColor;
        margin-right: 20px;
      }

      .logout {
        cursor: pointer;

        &:hover {
          color: @primaryColor;
        }
      }
    }
  }
}

.menu {
  background-color: #333;

  .el-menu {
    height: 40px;

    .el-menu-item {
      width: 80px;
      height: 40px;
      line-height: 40px;
      text-align: center;
    }
  }
}

.el-menu.el-menu--horizontal {
  border-color: #333;
}

.el-menu--horizontal > .el-submenu .el-submenu__title {
  height: 40px;
  line-height: 40px;
}

.el-carousel {
  img {
    width: 100%;
    height: 100%;
    object-fit: fill;
  }
}

.el-button--default:focus,
.el-button--default:hover {
  color: @primaryColor;
  background-color: rgba(39, 186, 155, 0.2);
  border-color: rgba(39, 186, 155, 0.2);
}

.el-button--primary:focus,
.el-button--primary:hover {
  color: #fff;
  background-color: rgba(39, 186, 155, 0.2);
  border-color: rgba(39, 186, 155, 0.2);
}

.el-button--primary {
  background-color: @primaryColor;
}

.el-button--primary:focus,
.el-button--primary:hover {
  opacity: 0.8;
  background-color: @primaryColor;
  border-color: @primaryColor;
}

.el-input.is-active .el-input__inner,
.el-input__inner:focus {
  border-color: @primaryColor;
}

.el-dialog__headerbtn:focus .el-dialog__close,
.el-dialog__headerbtn:hover .el-dialog__close {
  color: @primaryColor;
}
</style>
